import { useAPIUtils } from "@/components/APIUtilsProvider";
import EmptyListPlaceholder from "@/components/EmptyListPlaceHolder";
import { moreModals } from "@/components/moreModals";
import PageLayout from "@/components/PageLayout";
import RenderIf from "@/components/RenderIf";
import When from "@/components/When";
import {
  Button,
  Center,
  Flex,
  Group,
  Pagination,
  Paper,
  Select,
  Table,
  Text,
  TextInput,
} from "@mantine/core";
import { DateTimePicker } from "@mantine/dates";
import { useForm } from "@mantine/form";
import { IconSearch } from "@tabler/icons-react";
import dayjs from "dayjs";
import { useImmer } from "use-immer";

import UserPill from "@/components/UserPill";
import StatusRenderer from "./StatusRenderer";

export default function AfterSalesList() {
  const {
    restGET,
    tanstackQuery,
    tanstackInvalidate,
    restPOST,
    restPUT,
    restDELETE,
  } = useAPIUtils();

  const confirmHeadQuarterRefunded = async (id) => {
    await restPUT(
      `/api/admin/afterSales/${id}?action=CONFIRM_HEAD_QUARTER_REFUNDED`
    );
    tanstackInvalidate(`/api/admin/afterSales`);
    tanstackInvalidate(`/api/admin/afterSales/${id}`);
  };

  const [pagingCondition, setPagingCondition] = useImmer({
    targetStatus: "",
    orderId: "",
    start: dayjs().subtract(7, "days").toDate(),
    end: new Date(),
    pageIndex: 0,
    pageSize: 10,
  });

  const searchForm = useForm({
    mode: "uncontrolled",
    initialValues: {
      start: dayjs().subtract(7, "days").toDate(),
      end: new Date(),
      orderId: "",
      targetStatus: "",
    },
    validate: {},
  });

  const search = (values) => {
    tanstackInvalidate(`/api/admin/afterSales`);
    setPagingCondition({
      ...values,
      pageSize: pagingCondition.pageSize,
      pageIndex: 0,
    });
  };

  const aftersalesQuery = tanstackQuery(`/api/admin/afterSales`, {
    ...pagingCondition,
    targetStatus: pagingCondition.targetStatus || "",
    start: dayjs(pagingCondition.start).format("YYYY-MM-DDTHH:mm:ss"),
    end: dayjs(pagingCondition.end).format("YYYY-MM-DDTHH:mm:ss"),
    pageNo: pagingCondition.pageIndex,
    pageSize: pagingCondition.pageSize,
  });

  const totalPages = aftersalesQuery.data?.totalPages;
  const rows = aftersalesQuery.data?.content.map((aftersales, index) => (
    <Table.Tr key={index}>
      <Table.Td>
        <Text>{index + 1}</Text>
      </Table.Td>

      <Table.Td>
        <UserPill user={aftersales.buyer} />
      </Table.Td>
      <Table.Td>
        <UserPill user={aftersales.firstSeller} />
      </Table.Td>
      <Table.Td>
        {dayjs(aftersales.createdAt).format("YYYY/MM/DD HH:mm")}
      </Table.Td>
      <Table.Td>
        {aftersales.status == "APPROVED" && !aftersales.headQuarterRefunded ? (
          <Text>{`是（${aftersales.headQuarterRefundAmount}元）`}</Text>
        ) : (
          <Text c={"dimmed"}>否</Text>
        )}
      </Table.Td>
      <Table.Td>
        <StatusRenderer status={aftersales.status} />
      </Table.Td>
      <Table.Td>
        <Group>
          <RenderIf auth="OrderRelated">
            <Button
              size="xs"
              onClick={() =>
                moreModals.openDefaultConfirmModal({
                  title: `确认代表您已收到退货，并已经支付给店铺退款${aftersales.headQuarterRefundAmount}元。`,
                  onConfirm: () => {
                    confirmHeadQuarterRefunded(aftersales.id);
                  },
                })
              }
              disabled={
                aftersales.status !== "APPROVED" ||
                aftersales.headQuarterRefunded
              }
            >
              确认退款
            </Button>
          </RenderIf>
          <Button
            variant="subtle"
            size="xs"
            onClick={() =>
              window.open(`/afterSales/${aftersales.id}`, "_blank")
            }
          >
            详情
          </Button>
        </Group>
      </Table.Td>
    </Table.Tr>
  ));

  return (
    <PageLayout title={"售后申请列表"}>
      <form onSubmit={searchForm.onSubmit(search)}>
        <Flex
          mih={50}
          mb={44}
          gap="md"
          justify="flex-end"
          align="flex-end"
          direction="row"
          wrap="wrap"
        >
          <DateTimePicker
            description="时间开始"
            {...searchForm.getInputProps("start")}
            valueFormat="YYYY/MM/DD HH:mm"
            w={200}
          />
          <DateTimePicker
            description="时间结束"
            {...searchForm.getInputProps("end")}
            valueFormat="YYYY/MM/DD HH:mm"
            w={200}
          />
          <TextInput
            clearable
            placeholder="请输入完整订单号"
            label="订单号"
            {...searchForm.getInputProps("orderId")}
          />
          <Select
            clearable
            placeholder="默认全部"
            label="状态"
            {...searchForm.getInputProps("targetStatus")}
            data={[
              { label: "待审批", value: "PENDING" },
              { label: "已通过", value: "APPROVED" },
              { label: "已驳回", value: "REJECTED" },
            ]}
          />

          <Button type="submit" rightSection={<IconSearch size={14} />}>
            搜索
          </Button>
        </Flex>
      </form>

      <When condition={rows?.length > 0}>
        <Paper p={"md"}>
          <Table verticalSpacing={"sm"}>
            <Table.Thead>
              <Table.Tr>
                <Table.Th w={"3%"}></Table.Th>
                <Table.Th w={"15%"}>申请人</Table.Th>
                <Table.Th w={"30%"}>经营店铺</Table.Th>
                <Table.Th w={"10%"}>申请时间</Table.Th>
                <Table.Th w={"15%"}>等待总部退款</Table.Th>
                <Table.Th w={"15%"}>状态</Table.Th>
                <Table.Th>操作</Table.Th>
              </Table.Tr>
            </Table.Thead>
            <Table.Tbody>{rows}</Table.Tbody>
          </Table>
        </Paper>
        <Center mt={40}>
          <Pagination
            total={totalPages}
            value={pagingCondition.pageIndex + 1}
            onChange={(e) => {
              setPagingCondition({ ...pagingCondition, pageIndex: e - 1 });
            }}
          />
        </Center>
      </When>
      <When condition={rows?.length == 0}>
        <EmptyListPlaceholder />
      </When>
    </PageLayout>
  );
}
